package cn.kust.apiuser.service.impl;

import cn.kust.apiuser.service.ITokenService;
import cn.kust.microtourismcommon.constant.CommonStatusEnum;
import cn.kust.microtourismcommon.constant.TokenConstants;
import cn.kust.microtourismcommon.pojo.dto.ResponseResult;
import cn.kust.microtourismcommon.pojo.dto.TokenResult;
import cn.kust.microtourismcommon.pojo.response.TokenResponse;
import cn.kust.microtourismcommon.util.JwtUtils;
import cn.kust.microtourismcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author WY
 * @data 2022/7/21 10:24
 **/
@Service
public class ITokenServiceImpl implements ITokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshTokenSrc){
        //解析旧的refreshToken
        TokenResult tokenResult = JwtUtils.checkToken(refreshTokenSrc);
        if (tokenResult == null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        String userId = tokenResult.getUserId();


        //读取redis中的refreshtoken
        String refreshTokenKey  = RedisPrefixUtils.generatorTokenKey(phone, identity,TokenConstants.REFRESH_TOKEN_TYPE);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        //校验双token
//        如果redis不匹配
        if ((!StringUtils.hasLength(refreshTokenRedis)) || !refreshTokenSrc.trim().equals(refreshTokenRedis.trim())) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        //生成双token
        String refreshToken = JwtUtils.generatorToken(phone, identity,userId, TokenConstants.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone, identity,userId, TokenConstants.ACCESS_TOKEN_TYPE);

        //双token存入redis
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);

//        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 20, TimeUnit.SECONDS);
//        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken,31,TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken,160,TimeUnit.SECONDS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }

}
